<template>
  <div id="userLoginPage">
    <h2 class="title">{{ APP_TITLE }}</h2>
    <div class="desc">{{ APP_DESCRIPTION }}</div>
    <a-form :model="formState" @finish="onFinish" @finishFailed="onFinishFailed">
      <a-form-item
        label="用户账号"
        name="userAccount"
        :rules="[
          { required: true, message: '请输入用户账号!', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9_-]+$/,
            message: '用户名只能包含字母、数字、下划线或连字符',
            trigger: 'blur',
          },
        ]"
      >
        <a-input
          v-model:value="formState.userAccount"
          placeholder="请输入用户账号!"
          autocomplete="username"
        >
          <template #prefix>
            <UserOutlined class="site-form-item-icon" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item
        label="用户密码"
        name="userPassword"
        :rules="[
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          // {
          //   pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$/,
          //   message: '密码必须包含大小写字母、数字和特殊字符，长度在8到16位之间',
          //   trigger: 'blur',
          // },
        ]"
      >
        <!--        autocomplete="current-password" 告诉浏览器填充当前密码-->
        <a-input-password
          v-model:value="formState.userPassword"
          placeholder="请输入用户密码"
          autocomplete="current-password"
        >
          <template #prefix>
            <LockOutlined class="site-form-item-icon" />
          </template>
        </a-input-password>
      </a-form-item>
      <!-- 可选：添加验证码 -->
      <!-- <a-form-item label="验证码" name="captcha" :rules="[{ required: true, message: '请输入验证码!' }]">
        <a-input v-model:value="formState.captcha" placeholder="请输入验证码">
          <template #suffix>
            <img :src="captchaSrc" alt="验证码" @click="refreshCaptcha" />
          </template>
        </a-input>
      </a-form-item> -->

      <div class="tips">
        <RouterLink to="/register">立即注册</RouterLink>
      </div>
      <a-form-item>
        <a-button
          :loading="loading"
          :disabled="disabled"
          type="primary"
          html-type="submit"
          style="width: 100%"
          @keyup.enter="onSubmit"
        >
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive } from 'vue'
import { LockOutlined, UserOutlined } from '@ant-design/icons-vue'
import { getLoginUserUsingGet, userLoginUsingPost } from '@/api/userController'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { useRoute, useRouter } from 'vue-router'
import { APP_DESCRIPTION, APP_TITLE } from '@/config/global.js'

const APP_TITLE11 = import.meta.env.VITE_APP_TITLE

const formState = reactive<API.UserLoginRequest>({
  userAccount: '',
  userPassword: '',
})

const loading = ref(false)

const loginUserStore = useLoginUserStore()
// 返回路由器实例。相当于在模板中使用 $router。
const router = useRouter()
// 返回当前的路由地址。相当于在模板中使用 $route。
const route = useRoute()

const onFinish = async (values: FormState) => {
  try {
    loading.value = true
    const res = await userLoginUsingPost(values)
    console.log(res)
    if (res.code === 0 || res.code === 200) {
      await loginUserStore.getLoginUser()

      // ---修复问题：http://localhost:5173/http://localhost:5173/admin/picture/pictureManage
      // 清理 redirect 路径，移除可能存在的协议和主机部分
      let redirect = route.query.redirect as string | undefined

      if (redirect) {
        // 移除任何前缀的协议和主机部分
        const url = new URL(redirect, window.location.origin)
        redirect = url.pathname + url.search + url.hash
      }

      console.log('redirect', redirect)
      await router.push({
        path: redirect ?? '/',
        replace: true, // 确保导航后不会留下历史记录
      })
      message.success('登录成功')
    }
  } catch (error) {
    message.error(`登录失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}

const disabled = computed(() => {
  return !(formState.userAccount && formState.userPassword)
})

// 键盘事件处理函数
const onSubmit = () => {
  // 这里可以调用表单验证或者直接提交
}
</script>

<style scoped>
#userLoginPage {
  max-width: 360px;
  margin: 0 auto;
  padding: 24px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #fff;
}
.title {
  text-align: center;
  margin-bottom: 16px;
  font-size: 24px;
}
.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 24px;
}
.tips {
  margin-bottom: 16px;
  text-align: right;
  font-size: 13px;
}
.site-form-item-icon {
  color: rgba(0, 0, 0, 0.25);
}
</style>
